package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.LogBean;
import com.project.bean.RoleBean;
import com.project.bean.UserBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.ILogMapper;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserServiceImp implements IUserService {
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private ILogMapper logMapper;
    @Autowired
    private IGradeMapper gradeMapper;


    @Override
    public UserBean login(String username, String password) {
        UserBean user =  this.findUserByUserName(username);

        Md5Hash md5Hash = new Md5Hash(password,user.getSalt(),1024);
        //登录用户，返回对象
        QueryWrapper<UserBean> query = new QueryWrapper<UserBean>();
        query.eq("u_userName",username);
        query.eq("u_password",md5Hash.toHex());
        UserBean userBean = userMapper.selectOne(query);
        if (userBean != null) {
            //获取用户的权限集合
            List<GradeBean> gradeBeanList = userMapper.findByUser(userBean.getUserId());
            //设置用户的权限集合
            userBean.setGradeList(gradeBeanList);
            //日志添加
            logMapper.insert(new LogBean(LocalDate.now(),"用户"+userBean.getUserName()+"在"+ LocalTime.now() +"登录系统"));
            return userBean;
        }
        return userBean;
    }

    @Override
    public IPage<UserBean> findUserByItem(Integer pageNO, String username) {
        QueryWrapper<UserBean> query = new QueryWrapper<UserBean>();
        if (username!= null && !username.equals("")) {
            query.like("u_userName",username);
            return userMapper.selectPage(new Page<>(pageNO,3),query);
        }
        return userMapper.selectPage(new Page<>(pageNO,3),null);
    }

    @Override
    public UserBean findUserByUserName(String username) {
        QueryWrapper<UserBean> query = new QueryWrapper<>();
        query.eq("u_userName",username);
        UserBean userBean = userMapper.selectOne(query);

        List<RoleBean> roles = userMapper.findRoleByUserId(userBean.getUserId());
        List<GradeBean> grades = userMapper.findByUser(userBean.getUserId());

        userBean.setRoleList(roles);
        userBean.setGradeList(grades);

//        QueryWrapper<RoleBean> queryR = new QueryWrapper<>();
//        queryR.eq("fk_userId",userBean.getUserId());
//        List<RoleBean> roles = roleMapper.selectList(queryR);
//
//        userBean.setRoleList(roles);
//

        return userBean;
    }

    @Override
    public List<GradeBean> findAll() {
        return gradeMapper.selectList(null);
    }

    @Override
    public List<GradeBean> findByRoleIds(Integer[] roleIds) {
        if (roleIds.length > 0){
            return userMapper.findByRoleIds(roleIds);
        }
        return null;
    }


    @Override
    public void addUser(UserBean userBean,Integer[] roleIds) {
        //先根据传入用户的用户名，去数据库进行判断是否存在
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_userName",userBean.getUserName());
        UserBean userBean1 = userMapper.selectOne(qw);
        //1、只在user_role中添加就行
        //2、获取role集合
        //3、获取grade集合
        if (userBean1 == null && roleIds.length>0){
            //2、获取role集合
            List<RoleBean> roleBeanList = new ArrayList<>();
            for (Integer roleId : roleIds){
                RoleBean roleBean = roleMapper.selectById(roleId);
                roleBeanList.add(roleBean);
            }

            //3、获取grade集合
           List<GradeBean> gradeBeanList = userMapper.findByRoleIds(roleIds);

            userBean.setGradeList(gradeBeanList);
            userBean.setRoleList(roleBeanList);
            //设置加密
            userBean.setSalt(this.getSalt());
            Md5Hash md5Hash = new Md5Hash(userBean.getPassword(), userBean.getSalt(), 1024);

            //添加属性
            userBean.setGradeList(gradeBeanList);
            userBean.setRoleList(roleBeanList);
            userBean.setPassword(md5Hash.toHex());
            userMapper.insert(userBean);
            //1、只在user_role中添加就行
            userMapper.addUserRoleByUserId(userBean.getUserId(),roleIds);
        }else {
            System.out.println("已存在");
        }
    }

    private String getSalt() {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int index = (int) (Math.random() * str.length());
            sb.append(str.charAt(index));
        }
        return sb.toString();
    }

    @Override
    public void delUser(Integer userId) {
        userMapper.delUser(userId);
    }

    @Override
    public UserBean findByUserId(Integer userId) {
        QueryWrapper<UserBean> qw = new QueryWrapper<UserBean>();
        qw.eq("pk_userId",userId);
        UserBean userBean = userMapper.selectOne(qw);
        List<GradeBean> gradeBeanList = userMapper.findByUser(userId);
        List<RoleBean> roleBeanList = userMapper.findRoleByUserId(userId);
        userBean.setGradeList(gradeBeanList);
        userBean.setRoleList(roleBeanList);
        return userBean;
    }

    @Override
    public void updateRoleByUserId(Integer userId, Integer[] roleIds) {
        if (roleIds != null && roleIds.length!=0 && userId != 0) {
            //先通过用户id删除中间表相关信息，再添加新的角色信息
            userMapper.delUserRoleByUserId(userId);
            userMapper.addUserRoleByUserId(userId, roleIds);
        }
    }

    @Override
    public void updatePwd(Integer userId, String newPassword) {
        QueryWrapper<UserBean> qw = new QueryWrapper<UserBean>();
        qw.eq("pk_userId",userId);
        UserBean user = userMapper.selectOne(qw);
        if (newPassword!=null && !newPassword.equals("") && !user.getPassword().equals(newPassword)){
            user.setPassword(newPassword);
            userMapper.updateById(user);
        }

    }
}
